import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

// 环境变量
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api';
const API_TIMEOUT = parseInt(import.meta.env.VITE_API_TIMEOUT || '10000');

// 响应数据类型
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
}

// 创建axios实例
const http: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: API_TIMEOUT,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    // 添加token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    // 添加时间戳防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now(),
      };
    }
    
    console.log('Request:', config.method?.toUpperCase(), config.url, config.data || config.params);
    return config;
  },
  (error) => {
    console.error('Request Error:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    console.log('Response:', response.config.url, response.data);
    
    // 统一处理响应
    const { data } = response;
    if (data.code === 0 || data.code === 200) {
      return response;
    } else {
      // 业务错误
      const error = new Error(data.message || '请求失败');
      (error as any).code = data.code;
      return Promise.reject(error);
    }
  },
  (error) => {
    console.error('Response Error:', error);
    
    // 处理HTTP错误
    if (error.response) {
      const { status, data } = error.response;
      
      switch (status) {
        case 401:
          // 未授权，清除token并跳转登录
          localStorage.removeItem('token');
          window.location.href = '/login';
          break;
        case 403:
          console.error('权限不足');
          break;
        case 404:
          console.error('请求的资源不存在');
          break;
        case 500:
          console.error('服务器内部错误');
          break;
        default:
          console.error(`请求失败: ${status}`);
      }
      
      error.message = data?.message || `HTTP ${status} 错误`;
    } else if (error.request) {
      error.message = '网络连接失败';
    } else {
      error.message = '请求配置错误';
    }
    
    return Promise.reject(error);
  }
);

// 封装请求方法
export const request = {
  get: <T = any>(url: string, params?: any, config?: AxiosRequestConfig) =>
    http.get<ApiResponse<T>>(url, { params, ...config }),
  
  post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
    http.post<ApiResponse<T>>(url, data, config),
  
  put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
    http.put<ApiResponse<T>>(url, data, config),
  
  delete: <T = any>(url: string, config?: AxiosRequestConfig) =>
    http.delete<ApiResponse<T>>(url, config),
  
  patch: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
    http.patch<ApiResponse<T>>(url, data, config),
};

export default http; 